package servlet.stu;

import bean.Result;
import bean.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import service.UserService;
import service.UserServiceImpl;
import servlet.hou.HouLoginServlet;
import utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



//学生登陆
@WebServlet("/stu/login")
public class StuLoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=================学生登录==================");
        //根据输入框标签的name属性值去获取登录名和密码
        String stuName=request.getParameter("stuName");
        String stuPassword=request.getParameter("password");
        int stuId= Integer.parseInt(request.getParameter("stuId"));
        //记住密码


        UserService userService=new UserServiceImpl();
        //去查询用户输入的登录名和密码是否正确
        Student student=userService.findByPasswordAndId(stuPassword,stuId);

        if(student==null){
            //用户输入的名字或密码错误,即没找到该用户，跳转到登录页面，并给予提示信息
            Result result = new Result();
            result.failToLogin();
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);
            System.out.println(str);


        }else{
            //生成token
            Map<String,Object> claim = new HashMap<>();
            claim.put("stuId",student.getStuId());
            claim.put("stuName",student.getStuName());
            claim.put("buildId",student.getBuildId());
            claim.put("sex",student.getSex());
            claim.put("age",student.getAge());
            claim.put("email",student.getEmail());
            claim.put("dormitory",student.getDormitory());
            claim.put("bed",student.getBed());
            claim.put("college",student.getCollege());
            claim.put("profession",student.getProfession());
            Result result = new Result();
            result.success(JwtUtils.genToken(claim));
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);
            //说明用户的名字和密码正确，登录成功

            System.out.println("================跳转到学生主页面=============");
            new HouLoginServlet().insertOp("学生"+student.getStuName(),student.getStuId(),"学生"+student.getStuName()+"登陆了系统");



        }


    }
    }

